package com.wechat.quartz;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import com.wechat.pojo.AccessToken;
import com.wechat.pojo.ErrorEntity;
import com.wechat.utils.Constant;
import com.wechat.utils.WechatContext;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

@Component("accessTokenTask")
public class RefreshAccessTokenTask {

	public void refreshToken() {
		HttpGet get = null;
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;
		try {
			client = HttpClients.createDefault();

			String uri = Constant.ACCESS_TOKEN_URL;
			uri = uri.replaceAll("APPID", Constant.APPID);
			uri = uri.replaceAll("APPSECRET", Constant.APPSECRET);
			get = new HttpGet(uri);
			resp = client.execute(get);
			int status = resp.getStatusLine().getStatusCode();
			if (status >= 200 && status < 300) {
				HttpEntity entity = resp.getEntity();
				String content = EntityUtils.toString(entity);
				System.out.println(content);
				JSONObject jsonObject = JSONObject.fromObject(content);
				AccessToken token = new AccessToken();
				if (jsonObject.getString("access_token") != null) {
					token.setAccessToken(jsonObject.getString("access_token"));
					token.setExpiresIn(jsonObject.getInt("expires_in"));
					System.out.println(token.getAccessToken() + "," + token.getExpiresIn());
					WechatContext.setAccessToken(token.getAccessToken());
				} else {
					ErrorEntity ee = new ErrorEntity();
					ee.setErrcode(jsonObject.getString("errcode"));
					ee.setErrmsg(jsonObject.getString("errmsg"));
					System.out.println(ee.getErrcode() + "," + ee.getErrmsg());
					refreshToken();
				}

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resp != null)
					resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
